#include "iplist.h"

list_p iplists = 0;

void iplist_clean( void )
{
    list_p list;

    for( list = iplists ; list ; ) {
        list_p tlist = list;
        list = list->next;
        //timeout = 2 m = 120 s = 120000 ms
        if( GetTickCount( ) - ((iplist_p)tlist->data)->lasttick > 120 * 1000 )
            iplist_rem( tlist );
    }
}

iplist_p iplist_add( uint16_t id )
{
    int add = 0;
    iplist_p iplist = iplist_find( id );
    if( !iplist ) {
        iplist = calloc( 1, sizeof(iplist_t) );
        add = 1;
        iplist->data = 0;
        iplist->data_finished = 0;
        iplist->length = 0;
        iplist->id = id;
    }

    iplist->lasttick = GetTickCount( );

    if( add )
        return list_add( &iplists, (data_p) iplist )->data;
    else
        return iplist;
}

int iplist_rem( list_p list )
{
    if( !list )
        return 0;

    if( ((iplist_p)list->data)->data )
        free( ((iplist_p)list->data)->data );
    if( ((iplist_p)list->data)->data_finished )
        free( ((iplist_p)list->data)->data_finished );

    return list_rem( &iplists, list );
}

iplist_p iplist_find( uint16_t id )
{
    list_p list = iplist_list( id );

    if( list )
        return list->data;

    return 0;
}

list_p iplist_list( uint16_t id )
{
    list_p list;

    for( list = iplists ; list ; list = list->next )
        if( ((iplist_p)list->data)->id == id )
            return list;

    return 0;
}
